package com.by.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.by.admin.mapper.UserLoginMapper;
import com.by.admin.service.LoginService;
import com.by.model.Service.Impl;
import com.by.model.admin.dtos.UserLoginDto;
import com.by.model.admin.dtos.ZcDto;
import com.by.model.admin.pojo.ApUser;
import com.by.model.common.dtos.ResponseResult;
import com.by.model.common.enums.AppHttpCodeEnum;
import com.by.utils.common.AppJwtUtil;
import com.by.utils.common.BCrypt;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;

@Service
public class LoginServiceImpl extends Impl<UserLoginMapper, ApUser> implements LoginService {

    @Autowired
    private UserLoginMapper userLoginMapper;

    @Override
    public ResponseResult login(UserLoginDto dto) {
        //1.检查参数
        if (StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"用户名密码不能为空");
        }
        QueryWrapper<ApUser> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ApUser::getName,dto.getName());
        List<ApUser> list = list(wrapper);
        if (list != null && list.size() == 1) {
            ApUser apUser = list.get(0);
            String digest = DigestUtils.md5DigestAsHex((dto.getPassword()).getBytes());
            if (apUser.getPswd().equals(digest)){
                HashMap<Object, Object> map = Maps.newHashMap();
                apUser.setPswd("");
                map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                map.put("user",apUser);
                return ResponseResult.okResult(map);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }

    }

    @Override
    public ResponseResult zhuce(ZcDto dto) {
        ApUser apUser = new ApUser();
        if (dto!= null){
            apUser.setName(dto.getName());
            apUser.setPswd(DigestUtils.md5DigestAsHex((dto.getPassword()).getBytes()));
            apUser.setRole(dto.getRole());
            save(apUser);
        }
        return ResponseResult.okResult(AppHttpCodeEnum
        .SUCCESS + "注册成功");
    }


}
